#include "page_login.h"
#include "ui_page_login.h"
#include "dlg_register.h"
#include"mainwindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include "supsql.h"

Page_Login::Page_Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page_Login)
{
    ui->setupUi(this);
    connect(ui->ButtonLogin, SIGNAL(clicked()), this, SLOT(on_ButtonLogin_clicked));
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(on_pushButton_clicked));
}

Page_Login::~Page_Login()
{
    delete ui;
}

void Page_Login::on_btnExit_clicked()
{
    exit(0);
}

void Page_Login::on_ButtonLogin_clicked()
{
    ui->warningName->setText("");
    ui->warningPwd->setText("");
    QString user =ui->EditName->text();
    QString pwd = ui->EditPassword->text();
    if(user == ""&&pwd == "")
    {
        ui->warningName->setText("用户名不能为空");
        ui->warningPwd->setText("密码不能为空");
        QPalette pe;
        pe.setColor(QPalette::WindowText,Qt::red);
        ui->warningName->setPalette(pe);
        ui->warningPwd->setPalette(pe);
        return;
    }
    else if(user == "")
    {
        ui->warningName->setText("用户名不能为空");
        QPalette pe;
        pe.setColor(QPalette::WindowText,Qt::red);
        ui->warningName->setPalette(pe);
        return;
    }
    else if(pwd == "")
    {
        ui->warningPwd->setText("密码不能为空");
        QPalette pe;
        pe.setColor(QPalette::WindowText,Qt::red);
        ui->warningPwd->setPalette(pe);
        return;
    }
    else
    {
        //数据库查找账号和密码
        QString str = QString("select * from worker");
        auto ptr = supsql::getinstance();
        QSqlQuery query;
        query.exec(str);
        if(ptr->getUserCnt()==0)
        {
            QMessageBox::warning(nullptr,"error","数据库为空");
            return;
        }
        while (query.next())
        {
            QString SqlName = query.value(2).toString();
            QString SqlPwd = query.value(3).toString();
            QString Aur = query.value(6).toString();
            if(user == SqlName && pwd == SqlPwd)
            {

                if(Aur == "admin")
                {
                    QMessageBox::information(nullptr,"OK","管理员登录");
                }
                else
                {
                    QMessageBox::information(nullptr,"OK","用户登录");
                }
                QString SqlUserName = query.value(1).toString();
                Aur.append(QString(":%1").arg(SqlUserName));
                emit sendLoginSuccess(Aur);//成功就进入主界面
                this->hide();
                return;
            }
        }
        QMessageBox::warning(nullptr,"Error","用户名或密码错误");
        ui->EditName->clear();
        ui->EditPassword->clear();
    }
}

void Page_Login::on_pushButton_clicked()
{
    emit enter_register();
}
